#!/bin/bash

# 变量组
echo -e "\r项目路径----$AppHome"
echo -e "\r环境变量----$Env"
echo -e "\r内网SLB虚拟主机组ID----$LanprodVsgid"
echo -e "\r内网SLB虚拟主机组名称----$LanprodVsgname"
echo -e "\r外网SLB虚拟主机组ID----$WanprodVsgid"
echo -e "\r外网SLB虚拟主机组名称----$WanprodVsgname"
echo -e "\r服务名称----$AppName"
echo -e "\r服务端口号----$AppPort"
echo -e "\r服务管理端口号----$MonitPort"
echo -e "\rARMS开关----$Arms"
echo -e "\rJVM内存大小值----$JvmMem"
echo -e "\r数据源加密----$Encry"

# 变量固化
echo -e 'export AppName='$AppName'
export AppHome='$AppHome'
export AppPort='$AppPort'
export MonitPort='$MonitPort'
export Env='$Env'
export LanprodVsgid='$LanprodVsgid'
export LanprodVsgname='$LanprodVsgname'
export WanprodVsgid='$WanprodVsgid'
export WanprodVsgname='$WanprodVsgname'
export Arms='$Arms'
export JvmMem='$JvmMem'
export Encry='$Encry'' >${AppHome}/${AppName}/init_deploy.sh
chmod +x ${AppHome}/${AppName}/init_deploy.sh




# 根据环境变量生成JVM参数
if [ "$Env"x = "prod"x -a "$Arms"x = "Y"x ]; then
    JAVA_OPTS="-Xms${JvmMem} -Xmx${JvmMem} \
    -XX:NewRatio=1 \
    -XX:+UseG1GC \
    -XX:+HeapDumpOnOutOfMemoryError \
    -XX:HeapDumpPath=dump.hprof \
    -XX:+PrintGCDetails \
    -XX:+PrintGCTimeStamps \
    -XX:+PrintHeapAtGC \
    -XX:+PrintGCApplicationStoppedTime \
    -XX:+PrintReferenceGC \
    -Dcom.sun.management.jmxremote.authenticate=false \
    -Dcom.sun.management.jmxremote.ssl=false \
    -javaagent:/root/.arms/agent/arms-bootstrap-1.7.0-SNAPSHOT.jar \
    -Darms.licenseKey=i0xn2zgi7b@bc166826d291e15 \
    -Darms.appName=pro-${AppName}"
wget -O- http://arms-apm-hangzhou.oss-cn-hangzhou.aliyuncs.com/install.sh | sh && ~/.arms/supervisor/cli.sh i0xn2zgi7b@bc166826d291e15 pro-${AppName}
else
    JAVA_OPTS="-Xms${JvmMem} \
    -Xmx${JvmMem} \
    -XX:NewRatio=1"
fi

echo -e "\rJVM参数----$JAVA_OPTS"
HEALTH_CHECK_URL=http://127.0.0.1:${MonitPort}/actuator/health
SHUTDOWN_URL=http://127.0.0.1:${MonitPort}/actuator/shutdown
PROG_NAME=$0                                                         # 脚本名称
ACTION=$1                                                            # 启动参数
APP_START_TIMEOUT=120
START_LOG=${AppHome}/${AppName}/start.log
SID=`curl -s http://100.100.100.200/latest/meta-data/instance-id`

# 用法
usage() {
    echo -e "\r使用方法: ${PROG_NAME} {start|stop|restart}"
    exit 2
}

# 健康检查
health_check() {
    exptime=0
    echo -e "\r健康检查地址: ${HEALTH_CHECK_URL}"
    while true
        do
            status_code=`/usr/bin/curl -L -o /dev/null --connect-timeout 5 -s -w %{http_code}  ${HEALTH_CHECK_URL}`
            echo -e "\r健康检查返回 $status_code"
            if [ "$status_code" != "200" ]; then
                echo -e "\r服务未启动"
            else
                echo -e "\r健康检查返回 $status_code"
                curl -s ${HEALTH_CHECK_URL}|jq .status|grep -i up
                if [ "$?" == "0" ];then
                    echo -e "\r服务启动成功!"
                    break
                fi
            fi
            sleep 1
            ((exptime++))

            echo -e "\r等待健康检查时间: $exptime..."

            if [ $exptime -gt ${APP_START_TIMEOUT} ]; then
                echo -e "\r服务启动失败"
                exit 1
            fi
        done
    echo -e "\r健康检查 ${HEALTH_CHECK_URL} 通过"
}

# 设置内网SLB权重
lan_setvservergroupattribute() {
    while true
        do
            echo -e "\r开始设置内网SLB权重为 $1"
            aliyun slb SetVServerGroupAttribute --region cn-hangzhou --RegionId cn-hangzhou --VServerGroupId ${LanprodVsgid} --VServerGroupName ${LanprodVsgname} --BackendServers '[{ "ServerId": "'"${SID}"'", "Weight": "'"${1}"'", "Type": "ecs", "Port":"'"${AppPort}"'" }]'
            if [ "$?" == "0" ]; then
                echo -e "\r设置内网SLB权重成功"
                break
            else
                echo -e "\r设置内网SLB权重失败"
            fi
        done
}

# 设置外网SLB权重
wan_setvservergroupattribute() {
    while true
        do
            echo -e "\r开始设置外网SLB权重为 $1"
            aliyun slb SetVServerGroupAttribute --region cn-hangzhou --RegionId cn-hangzhou --VServerGroupId ${WanprodVsgid} --VServerGroupName ${WanprodVsgname} --BackendServers '[{ "ServerId": "'"${SID}"'", "Weight": "'"${1}"'", "Type": "ecs", "Port":"'"${AppPort}"'" }]'
            if [ "$?" == "0" ]; then
                echo -e "\r设置外网SLB权重成功"
                break
            else
                echo -e "\r设置外网SLB权重失败"
            fi
        done
}

# 启动app
start_application() {
    echo -e "\r开始启动 ${AppName} 服务"
    if [ "$Encry" = "Null" ]; then
        nohup java -jar ${JAVA_OPTS} -Dio.netty.noPreferDirect=true ${AppHome}/${AppName}/${AppName}.jar > ${START_LOG} 2>&1 &
    else
        nohup java -jar ${JAVA_OPTS} -Djasypt.encryptor.password=${Encry} -Dio.netty.noPreferDirect=true ${AppHome}/${AppName}/${AppName}.jar > ${START_LOG} 2>&1 &
    fi
    echo -e "\r${AppName} 已启动"
}

# 停止app
stop_application() {
    checkjavapid=`jps -l| grep ${AppName} | awk '{print $1}'`   
    if [[ ! $checkjavapid ]];then
      echo -e "\r${AppName}未启动"
      return
    fi

    echo -e "\r开始停止 ${AppName} 服务"
    curl -s ${SHUTDOWN_URL} -X POST
    times=10
    for e in $(seq 10)
    do
        sleep 1
        COSTTIME=$(($times - $e ))
        checkjavapid=`jps -l| grep ${AppName} | awk '{print $1}'`
        if [[ $checkjavapid ]];then
            
            echo -e  "\r        -- 停止服务剩余 `expr $COSTTIME` 秒."
        else
            echo -e "\r服务已停止"
            break
        fi
    done
    echo -e "\r服务停止失败! 开始kill进程!"
    kill -9 $checkjavapid
    echo -e "\r服务 ${AppName} 进程 $checkjavapid 已被杀"
    
}

start() {
    start_application
    health_check
    #如果内网SLB虚拟主机组ID和外网SLB虚拟主机组ID都不为Null(有2个slb的情况).同时调整权重为100
    if [ "$LanprodVsgid" != "Null" -a "$WanprodVsgid" != "Null" ]; then
        lan_setvservergroupattribute 100
        wan_setvservergroupattribute 100
    #如果内网SLB虚拟主机组ID不为Null且外网SLB虚拟主机组ID为Null(只有1个内网SLb的情况).调整内网SLB权重为0
    elif [ "$LanprodVsgid" != "Null" -a "$WanprodVsgid" = "Null" ]; then
        lan_setvservergroupattribute 100
    else
        echo -e "\r没有SLB，无需调整!"
    fi
}

stop() {
    #如果内网SLB虚拟主机组ID和外网SLB虚拟主机组ID都不为Null(有2个slb的情况).同时调整权重为0
    if [ "$LanprodVsgid" != "Null" -a "$WanprodVsgid" != "Null" ]; then
        lan_setvservergroupattribute 0
        wan_setvservergroupattribute 0
    #如果内网SLB虚拟主机组ID不为Null且外网SLB虚拟主机组ID为Null(只有1个内网SLb的情况).调整内网SLB权重为0
    elif [ "$LanprodVsgid" != "Null" -a "$WanprodVsgid" = "Null" ]; then
        lan_setvservergroupattribute 0
    else
        echo -e "\r没有SLB，无需调整!"
    fi
    stop_application
    sleep 3
}


# main
case "$ACTION" in
    start)
        start
    ;;
    stop)
        stop
    ;;
    restart)
        stop
        start
    ;;
    *)
        usage
    ;;
esac
